//ajax错误码对照
var ajaxErrorCode = {'12007':'请检查您是否已经连接到Internet','12029':'连接超时，请检查网络','500':'服务器内部错误','503':'服务不可用'};
/**
 * ajax请求全局设置
 */
$(document).ready(function(){
	$.ajaxSetup({
		beforeSend: function() {
			common.mask();
		},
		error:function(xhr, textStatus, errorThrown){
			defaultAjaxError(xhr, textStatus, errorThrown);
		},
		complete: function() {
			common.unmask();
		}
	});
	//设置同步索引的按钮链接事件 add by laiyd
	if($("#updateSolr_index").length > 0){
		$('#updateSolr_index').attr('href','javascript:void(0)\;');
	}
});
//默认的ajax错误处理
function defaultAjaxError(xhr, textStatus, errorThrown){
	common.showError({title: localeMsg.common.error, text: ajaxErrorCode[xhr.status] ? ajaxErrorCode[xhr.status] : xhr.status, errorMsg: xhr.responseText});
}
/**
 * 
 */
var common = {
	/**
	 * 自动调整左侧的高度与右侧等高;
	 */
	adjustLeftHeight:function(){
		$("#main_left").css({height:$("#main_content").outerHeight()-2})
	},
	/**
	 * 默认个人大头像
	 * @param {} element
	 */
	defaultMyPic:function(element,type){
		var picUrl = resourceURL+"/css/images/img_pic50x50.png";
		if(type && type=='upload')
		{
			picUrl = resourceURL+"/css/images/img_uploadpic.jpg";
		}else if(type && type=='noviewbig'){
			picUrl = resourceURL+"/css/images/img_uploadpic120.jpg";
		}else if(type && type=='noview'){
			picUrl = resourceURL+"/css/images/img_uploadpic50.jpg";
		}
		element.src = picUrl;
	},
	/**
	 * 表格宽度自适应
	 */
	adjustWidth: function(){
		var width = 0;
		var th ;
		$(".main_right_table_th").each(function(){
			var w = parseInt($(this).get(0).style.width);
			width += w;
			
			th = $(this);
		});
		$(th).parent('.main_right_table table').width(width);
		$(th).parent('.main_right_table table').css('overflow-x', 'auto');
	},

	/**
	 * 左侧菜单栏操作
	 */
	toggleMenu: function(){
		$(".nav_sub").unbind("click").click(function(){
			//$(this).siblings(".main_left_nav_content").hide();
			if ($(this).next("div").eq(0).is(":visible")) {
				$(this).next("div").eq(0).hide();
				$(this).removeClass("main_left_nav_on");
				$(this).addClass("main_left_nav_off");
			} else {
				$(this).next("div").eq(0).show();
				$(this).removeClass("main_left_nav_off");
				$(this).addClass("main_left_nav_on");
			}
		});
		
		// 扩展菜单点击事件
		$(".nav_ext").click(function(){
			$(this).siblings("ul").hide();
			$(this).siblings(".nav_ext").removeClass("main_left_nav_contentliw2");
			$(this).siblings(".nav_ext").addClass("main_left_nav_contentliw");
            if($(this).hasClass("main_left_nav_contentliw"))
			{//已关闭,点击则展开;
				$(this).next("ul").eq(0).animate({height: 'toggle', opacity: 'toggle'}, "slow");
				$(this).removeClass("main_left_nav_contentliw");
				$(this).addClass("main_left_nav_contentliw2");
			}else if($(this).hasClass("main_left_nav_contentliw2"))
			{//已展开,点击则关闭;
				$(this).removeClass("main_left_nav_contentliw2");
				$(this).addClass("main_left_nav_contentliw");
			}
		});
	},
	//分类操作
	toggleContent : function() {
		$(".main_Receipt_table_t").unbind("click").click(function(){
			if($(this).next("div").eq(0).attr("class") == "c") {
				if ($(this).next("div").next("div").eq(0).is(":visible")) {
					$(this).next("div").next("div").eq(0).animate({height: 'toggle', opacity: 'toggle'}, "slow");
					$(this).removeClass("main_Receipt_table_t");
					$(this).addClass("main_Receipt_table_td");
				} else {
					$(this).next("div").next("div").eq(0).animate({height: 'toggle', opacity: 'toggle'}, "slow");
					$(this).removeClass("main_Receipt_table_td");
					$(this).addClass("main_Receipt_table_t");
				}
			} else {
				if ($(this).next("div").eq(0).is(":visible")) {
					$(this).next("div").eq(0).animate({height: 'toggle', opacity: 'toggle'}, "slow");
					$(this).removeClass("main_Receipt_table_t");
					$(this).addClass("main_Receipt_table_td");
				} else {
					$(this).next("div").eq(0).animate({height: 'toggle', opacity: 'toggle'}, "slow");
					$(this).removeClass("main_Receipt_table_td");
					$(this).addClass("main_Receipt_table_t");
				}
			}
		});
	},
	
	/**
	 * 左侧菜单显隐操作
	 */
	packup : function() {
		$(".packup_left").toggle(function(){
			$(".main_left").hide();
			$(".packup_left").addClass("packup_left2");
			$("#main_content").removeClass("main_right");
			$("#main_content").addClass("main_right2");
			
			var imgUrl=resourceURL+"/css/images/packup_btn2.png";
			$("#hiddenImg").attr("src",imgUrl);
			$("#hiddenImg").attr("title","显示左侧菜单");
		}, function(){
			$(".main_left").attr("style","display:block");
			$(".packup_left").removeClass("packup_left2");
			$("#main_content").addClass("main_right");
			$("#main_content").removeClass("main_right2");
			var imgUrl=resourceURL+"/css/images/packup_btn.png";
			$("#hiddenImg").attr("src",imgUrl);
			$("#hiddenImg").attr("title","隐藏左侧菜单");
		});
	},
	

	
	/**
	 * 切换页签，根据选中页签值，显示相应的内容
	 * 如果不通过ajax请求加载内容，则根据页签值找到相应id的div，控制其显隐
	 * 页面元素格式如下：
	 * <div class="main_right_table_nav">
			<ul>
		    	<li class="c"><a href="javascript:void(0);" value="base"><em>合同信息</em></a></li>
		        <li><a href="javascript:void(0);" value="add"><em>补充信息</em></a></li>
		    </ul>
		</div>
		<div class="main_Receipt_table" id="base">合同信息...</div>
		<div class="main_Receipt_table" id="add">补充信息...</div>
	 * 如果某个页签需要对应的ajax请求加载内容，则在链接元素上添加url属性，并且可以添加cache=false属性每次点击都请求，示例如下：
	 * <div class="main_right_table_nav">
			<ul>
		    	<li class="c"><a href="javascript:void(0);" value="base"><em>合同信息</em></a></li>
		        <li><a href="javascript:void(0);" value="add" url="${base}/xxx/xxx"><em>补充信息</em></a></li>
		    </ul>
		</div>
		<div class="main_Receipt_table" id="base">合同信息...</div>
		<div class="main_Receipt_table" id="add">补充信息...</div>
	 * opt = {
	 * 		url : url,
	 * 		key : "key",	// 请求参数的键名
	 * 		callback : function(data, val){}
	 * }
	 */
	switchTab : function(opt) {
		var o = opt || {};
		$(".main_right_table_nav li").unbind("click");
		$(".main_right_table_nav li").click(function(){
			$(this).addClass("c");
			$(this).siblings().removeClass("c");
			var val = $(this).find("a").attr("value");
			var key = o.key || "key";
			var url = $(this).find("a").attr("url");
			var disableCache = 'false' == $(this).find("a").attr("cache");
			var param = {};
			param[key] = val;
			var pageSize = $("select[name='pageSize']").val();
			if(pageSize) param.pageSize = pageSize;
			if (o.url) {
				$.ajax({
					type : 'post',
					url : o.url,
					async:false,
					data : param,
					success : function(data) {
						if (o.callback) {
							o.callback.call(this, data, val);
						}
						else {
							$(".main_right_table").html("").html(data);
						}
					}
				});
			} else if(url){
				if ($("#" + val).html().length == 0 || disableCache == true){
					$.ajax({
						type : 'post',
						url : url,
						async:false,
						data : param,
						success : function(data) {
							$("#" + val).siblings(".main_Receipt_table").hide();
							$("#" + val).html("").html(data).show();
						}
					});
				} else {
					$("#" + val).siblings(".main_Receipt_table").hide();
					$("#" + val).show();
				}
			} else {
				if (o.callback) {
					o.callback.call(this, val);
				}
				else {
					$("#" + val).siblings(".main_Receipt_table").hide();
					$("#" + val).show();
				}
			}
			var onshow = $(this).find("a").attr("onshow");//在a标签上的回调
			if(onshow){
				eval(onshow).call($(this), $(this).find("a"));
			}
		});
	},
	/**
	 * 切换下拉菜单，根据选中菜单值，显示相应的内容
	 * 如果不通过ajax请求加载内容，则根据页签值找到相应id的div，控制其显隐
	 * 页面元素格式如下：
         <div class="modle_navgzhb">
         <div id="menuClick3" name="selectMenu" class=""><span name="text">全部确收单</span><span class="modle_rel">&nbsp;</span>
         <div class="modle_menu_list" id="vMenuList3">
          <div class="modle_menu_listli"><a href="javascript:void(0);" class="modle_menu_listlia" value="">全部确收单</a></div>
          <div class="modle_menu_listli"><a href="javascript:void(0);" class="modle_menu_listlia" value="1">拟稿</a></div>
          <div class="modle_menu_listli"><a href="javascript:void(0);" class="modle_menu_listlia" value="2">审批中</a></div>
          <div class="modle_menu_listli"><a href="javascript:void(0);" class="modle_menu_listlia" value="3">审批完成</a></div>
         </div>
         </div>
         </div>
	 *
	 * opt = {
	 * 		url : url,
	 * 		key : "key",	// 请求参数的键名
	 * 		callback : function(data){}
	 * }
	 */
	switchMenu : function(opt) {
		$("div[name='selectMenu']").unbind("click");
		$("div[name='selectMenu']").click(function(){
			if($(".modle_menu_list").is(":hidden")){
				$(".modle_menu_list").show();
			}else{
				$(".modle_menu_list").hide();
			} 
		});
		$(".modle_menu_listli").unbind("click");
		$(".modle_menu_listli").click(function(){
			if($(this).text()!=$("div[name='selectMenu']").find("span[name='text']").text()){
				$("div[name='selectMenu']").find("span[name='text']").text($(this).text());
				common.ajaxPost(opt,$(this));
			}
		});
	},
	
	ajaxPost:function(opt,obj){
		var o = opt || {};
		var key = o.key || "key";
		var param = {};
		var val = obj.find("a").attr("value");
		param[key] = val;
		var pageSize = $("select[name='pageSize']").val();
		if(pageSize) param.pageSize = pageSize;
		if (o.url) {
			$.ajax({
				type : 'post',
				url : o.url,
				async:false,
				data : param,
				success : function(data) {
					if (o.callback) {
						o.callback.call(this, data, val);
					}
					else {
						$(".main_right_table").html("").html(data);
					}
				},
				error:function(data, status, e){
					alert(status);
				}
			});
		} else {
			if (o.callback) {
				o.callback.call(this, val);
			}
			else {
				$("#" + val).siblings(".main_Receipt_table").hide();
				$("#" + val).show();
			}
		}
	},
	/**
	 * 滑动菜单
	 * o = {
	 * 		menu : "#menu",		// 菜单元素
	 * 		url : url,			// 菜单请求地址
	 * 		key : "status",		// 参数键名
	 * 		callback : function(view, val){}	//回调方法，view为视图，val为菜单参数值
	 * }
	 */
	slideMenu : function(o) {
		var _m = o.menu;
		var _k = o.key;
		$(_m).find("span").unbind("click").click(function(){
			$(".modle_menu_list").slideDown();
		});
		
		$(document).click(function(e) {
			var $c = $(e.target).closest(_m);
			if (!$c.is(_m)) {
				$(".modle_menu_list").slideUp();
			}
		});
		
		$(".modle_menu_listli").unbind("click").click(function(){
			$(_m).find("span:first").text($(this).text());
			var val = $(this).find("a").attr("value");
			var param = {};
			param[_k] = val;
			var pageSize = $("select[name='pageSize']").val();
			if(pageSize) param.pageSize = pageSize;
			
			if (o.url) {
				$.ajax({
					type : 'post',
					async : false,
					url : o.url,
					data : param,
					success : function(data) {
						$(".modle_menu_list").slideUp();
						$(".main_right_table").html("").html(data);
						if (o.callback) {
							o.callback.call(this, data, val);
						}
					},
					error:function(data, status, e){
						common.showTip({text:status});
					}
				});
			} else {
				if (o.callback) {
					$(".modle_menu_list").hide();
					o.callback.call(this, val);
				}
			}
		});
	},
	
	/**
	 * 弹出对话框
	 * param = {
	 * 		obj : "#id",			// 对话框元素，如<div id="id"></div>
	 * 		url : "/dd/ss,			// 异步加载对话框内容的请求地址
	 * 		param : {key : value},	// 请求参数
	 * 		title : "",				// 对话框标题
	 * 		width : 400,			// 宽度
	 * 		height : 200,			// 高度
	 * 		modal : true,			// 是否模式对话框
	 *      dbClick : false,         // 是否双击记录行选中记录，默认false
	 * 		confirm : function(){},	// 确认按钮回调事件
	 * 		cancel : function(){},	// 取消按钮回调事件
	 * 		confirmText : "Confirm",// 确认按钮文本
	 * 		cancelText : "Cancel",	// 取消按钮文本
	 * 		nobutton: true          // 不显示按钮
	 * }
	 */
	dialog : function(param) {
		param = param || {};
		// 只读字段且不是必填字段不响应事件
		if(param.field && $(param.field).data('readonly')){
			if(!($(param.field).data().validatebox && $(param.field).data().validatebox.options.required)){
				return;
			}
		}
		var _url = param.url;
		var _param = param.param;
		var _obj = param.obj;
		var _type = param.type || "post";
		if (_url && _url != "") {
			$.ajax({
				type : _type,
				data : _param,
//				async : param.async || false,
				url : _url,
				success : param.success || function(html) {
					activeloadMask(param);
					// 没有指定目标元素，则生成新div
					if($(_obj).length < 1) {
						var t = (new Date()).getTime();
						$("body").append('<div class="white_content" id="tempDL' + t + '"></div>');
						_obj = "#tempDL" + t;
					}
					$(_obj).append(html);
					show(param);
				},
				error : param.error || function(XMLHttpRequest, textStatus, errorThrown){
					if (_url.startWith(baseURL))
						common.showTip({text:textStatus + ":" + errorThrown});
					else {
						common.genSsoIframe(_url, function(){
							common.dialog(param);
						});
					}
				}
			});
		} else {
			show(param);
		}
		
		function show(param) {
			param.title = param.title || "";
			param.width = param.width || "auto";
			param.height = param.height || "auto";
			if(param.dbClick == undefined){
				param.dbClick = false;
			}
			if(!param.modal) param.modal = true;
			
			param.onClose = function(){
				destroyloadMask(param);
				$(".white_content").find("tr").off();
				$(_obj).dialog("destroy");
			};
			if(param.dbClick){
				$(".white_content").find("tr").on("dblclick",function(){
					$(this).find(":radio").attr("checked","checked");
					$(this).find(":checkbox").attr("checked","checked");
					var rtn = param.confirm.call(this, _obj);
					if (rtn != false) {
						$(".white_content").find("tr").off();
						destroyloadMask(param);
						$(_obj).dialog("destroy");
					}
					
				});
			}
			if(!param.nobutton){
				var buttons = [{
					id: "btn_dialog_confirm",
					text: param.confirmText || localeMsg.common.confirm,
					selected: true,
					handler: function(){
						if (param.confirm) {
							//如果是选择记录的弹框，最少要选择一条记录
							/*if($(".white_content").find(":radio").length > 0){
								if($(".white_content").find(":radio:checked").length == 0){
									common.showTip({title:localeMsg.common.prompt,text:localeMsg.common.selectMsg});
									return;
								}
							}else if($(".white_content").find(":checkbox").length > 0){
								if($(".white_content").find(":checkbox:checked").length == 0){
									common.showTip({title:localeMsg.common.prompt,text:localeMsg.common.selectMsg});
									return;
								}
							}*/
							// 表单填写需要通过验证才能提交
							var $form = $(_obj).find("form")
							if ($form.length > 0) {
								if ($form.find(".custom_invalid").length > 0
										|| !$form.form("validate")) {
									return;
								}
							}
							
							var rtn = param.confirm.call(this, _obj);
							if (rtn != false) {
								$(".white_content").find("tr").off();
								destroyloadMask(param);
								$(_obj).dialog("destroy");
							}
						} else {
							$(".white_content").find("tr").off();
							destroyloadMask(param);
							$(_obj).dialog("destroy");
						}
					}
				}, {
					id: "btn_dialog_cancel",
					text: param.cancelText || localeMsg.common.cancel,
					handler: function(){
						if (param.cancel) param.cancel.call(this, _obj);
						$(".white_content").find("tr").off();
						destroyloadMask(param);
						$(_obj).dialog("destroy");
					}
				}];
				if (param.buttons) {
					param.buttons = param.buttons.concat(buttons);
				} else {
					param.buttons = buttons;
				} 
			}
			
			$(_obj).dialog(param);
	
		}
	},
	
	/**
     * easyui确认对话框
     * @param {} message-信息
     * @param {} callback-回调函数
     * @param {} _argument-参数
     */
    confirmDialog : function(message, confirmFn, _argument, cancelFn) {
//    	activeloadMask();
    	
    	$(".panel-tool-close").off("click").on("click",function(){
	   		 destroyloadMask();
	   	});
    	var  argument=_argument;
    	$.messager.confirm('', message, function(r){
            if (r){
                if(argument){
                	
                	confirmFn.call(callback,argument);
				}else{
					
					confirmFn.call();
				}
            } else {
            	cancelFn = cancelFn || function() {};
            	cancelFn.call();
            }
//            destroyloadMask();
        });
    },
	
	/**
	 * 流程选人树
	 * opt = {
	 * 		obj : "#obj", // 事件绑定对象
	 * 		url : baseURL + "/orgUser/tree/actor",
	 * 		param : {actor : ""},
	 * 		title : "",
	 * 	 	rightText ： "已选人员",
	 * 		width : 320,
	 * 		height : 480,
	 * 		single : true, // 是否单选，默认单选
	 * 		confirm : function(data){}, // 回调函数，返回选中的节点
	 * }
	 */
	tree : function(opt) {
		opt.url = opt.url || baseURL + "/orgUser/tree/actor";
		opt.searchUrl=opt.searchUrl || baseURL + "/orgUser/tree/searchuser";
		var _o = opt.obj;
		var _single = opt.single; // 是否单选
		
		if (!_o) {
			opt.event = "none";
			_o = "body";
		}
		if (_single) {
			if(opt.onlyLeafSelect == null) {
				opt.onlyLeafSelect = true;
			}
		} else {
			opt.checkbox = true;
			opt.cascadeCheck = true;
		}
		$(_o).outree(opt);
	},
	/**
	 * 新的流程选人树
	 */
	actortree : function(opt) {
		opt.url = opt.url || baseURL + "/workflow/candidate";
		var _o = opt.obj;
		var _single = opt.single; // 是否单选
		
		if (!_o) {
			opt.event = "none";
			_o = "body";
		}
		if (_single) {
			opt.onlyLeafSelect = true;
		} else {
			opt.multi = true;
			opt.cascadeCheck = true;
		}
		opt.showDepartmentPath = false;
		$(_o).actortree(opt);
	},
	
	/**
	 * 提示框，可设置延时时间自动关闭
	 * o = {
	 * 		title : "提示标题",
	 * 		text : "提示内容",
	 * 		success : true/false/无  用于显示图标
	 * 		width : 240,
	 * 		height : 180,
	 * 		autoclose : true,	// 是否自动关闭
	 * 		timeout : 1500,		// 延时关闭时间
	 * 		refresh : false,	// 是否刷新父窗口
	 * 		close : false,		// 是否关闭主窗口
	 * 		callback : function(){}
	 *  }
	 */
	showTip : function(o) {
		o = o || {};
		var autoclose = o.autoclose == undefined ? true : o.autoclose; 
		var content = o.text || '';
		activeloadMask();
		var success = o.success === true;
		var fail = o.success === false;
		var t = (new Date()).getTime();
		if (success) {
			$("body").append('<div class="white_content" id="dialogdiv' + t 
					+ '"><div class="modle_popsigntips"><div class="modle_popsigntip modle_popsigntip02"><div class="modle_popsigntipt">'
					+ content + '</div></div></div>');
		} else if(fail) {
			$("body").append('<div class="white_content" id="dialogdiv' + t 
					+ '"><div class="modle_popsigntips"><div class="modle_popsigntip modle_popsigntip03"><div class="modle_popsigntipt">'
					+ content + '</div></div></div>');
		} else {
			$("body").append('<div class="white_content" id="dialogdiv' + t + '"><div class="modle_popsigntipt">' + content + '</div></div>');
		}
		
		// 弹出窗口
		$('#dialogdiv' + t).dialog({
			title: o.title || localeMsg.common.prompt,
			width: o.width || 320,
			height: o.height || 280,
			modal: true,
			onClose: function(){
				if (o.callback) {
					o.called=true;
					o.callback.call(this);
				}
			},
			buttons: [{
				text: localeMsg.common.confirm,
				handler: function(){
					if (o.callback) {
						o.called=true;
						var rtn = o.callback.call(this);
						if (rtn != false) {
							destroyloadMask();
						}
						$('#dialogdiv' + t).dialog("destroy");
						$('#dialogdiv' + t).remove();
					} else {
						destroyloadMask();
						$('#dialogdiv' + t).dialog("destroy");
						$('#dialogdiv' + t).remove();
					}
				}
			}]
		});
		
		// 延时自动关闭
		if (autoclose) {
			setTimeout(function(){
				if (o.callback && !o.called) {
					o.callback.call(this);
				}
				destroyloadMask();
				$('#dialogdiv' + t).dialog("destroy");$('#dialogdiv' + t).remove();
				if (o.refresh) {
					try{
						window.opener.location.reload();
					}catch (e) {
					}
				}
				if (o.close) {
					window.close();
				}
			}, o.timeout || 5000);
		}
	},
	showError : function(o) {
		o = o || {};
		var content = o.text || '';
		activeloadMask();
		var t = (new Date()).getTime();
		$("body").append('<div class="white_content" id="dialogdiv' + t 
				+ '"><div class="modle_popsigntips">'
				+ '<div id="errorMsg" style=""></div></div>');
		
		// 弹出窗口
		$('#dialogdiv' + t).dialog({
			title: o.title || localeMsg.common.prompt,
			width: o.width || 240,
			height: o.height || 180,
			modal: true,
			buttons: [{
				text: localeMsg.common.confirm,
				handler: function(){
					destroyloadMask();
					$('#dialogdiv' + t).dialog("destroy");
					$('#dialogdiv' + t).remove();
				}
			}]
		});
		
		if(o.errorMsg){
			$('#dialogdiv' + t).panel('resize',{
				width: 640,
				height: 400
			});
			$('#dialogdiv' + t).dialog('center');
			$("#errorMsg").empty().html(o.errorMsg);
		}
	},
	
	/**
	 * 生成控件元素
	 * o = {
	 * 		appendTo : "#id",		// 控件所属元素
	 * 		type : "dic",			// 控件类型；attachTree:附件类型多级字典树， dic:字典树，user:选人树，org:组织树，date:日期控件，acctree:安徽会计科目树，支持year参数
	 *                              datepicker:新的日期控件，不使用easyui，因为easyui的日期控件在界面有较多控件时性能差
	 * 									datetime:时间控件，sort:模板分类树，dicSelect：单级字典下拉，需要typeCode和name两个参数和width参数，支持onchange回调和onload回调，支持async参数用于控制ajax是否异步（默认true）
	 * 		data : "typeCode",		// 请求参数
	 * 		names : ["name1", "name2", "name3],	// 表单域控件name属性值数组
	 * 		values : ["val1", "val2", "val3"],	// 默认值，与names相对应
	 * 		confirm : function(data){},		// 回调方法
	 * }
	 */
	genWidget : function(o) {
		var _h = new Stringbuilder();
		var _obj = o.appendTo;
		var _t = o.type;
		var _ns = o.names || new Array();
		var _vs = o.values || new Array();
		
		if(_t == 'acctree'){
			genAcctree();
		}else if (_t == "dic") {
			genDictree();
		}
		else if (_t == "sort") {
			genSorttree();
		}
		else if (_t == "date" || _t == "datetime") {
			genDatetime();
		}else if( _t == "datepicker"){
			genDatepicker();
		}
		else if (_t == "user") {
			genUserTree();
		}else if(_t=="single"){
			genDic();
		}else if(_t == 'dicSelect'){
			genDicSelect();
		}else if(_t == 'org'){
			genOrgTree();
		}else if(_t == 'attachTree'){
			getAttachTree();
		}
		function genDicSelect(){
			var _n1 = _ns[0] || o.typeCode || "";
			var _n2 = _ns[1] || o.name || "";
			var async = o.async;
			if(async == undefined){
				async = true;
			}
			var width = o.width || 150;
			var t = (new Date()).getTime();
			var _v1 = _vs[0] || "";
			var selected = "";
			_h.append('<div class="xm_select xm_select4" style="width:' + width + 'px;">');
			_h.append('<select id="' + _n2 + t + '" name="' + _n2 + '" class="xm_selectin"><option value="">-- 请选择 --</option></select>');
			_h.append('</div>');
			$(_obj).append(_h.toString());
			var $this = $("#" + _n2 + t);
			if(o.onchange){
				$this.change(function(){
					var $seleted = $(this).find("option:selected");
					o.onchange.call(this, $seleted);
				});
			}
			$.ajax({
				url :  baseURL + "/dic/item",
				data: {typeCode: _n1},
				dateType:'json',
				async: async,
				success: function(data){
					for ( var i = 0; i < data.length; i++) {
						selected = "";
						if(_v1==data[i].code) selected = "selected='selected'";
						$('#' + _n2 + t).append('<option zh="'+data[i].name+'" en="'+data[i].nameEn+'" extvalue2="'+data[i].extValue2+'" extvalue="'+data[i].extValue+'" value="' + data[i].code + '" ' + selected + '>' + data[i].localeName + '</option>');
					}
					if(o.onload){
						o.onload.call($this, data);
					}
				}
			});
			
		}
		// 树形数据字典
		function genDic() {
			var _n1 = _ns[0] || o.pathName || "";
			var _n2 = _ns[1] || o.codeName || "";
			var _n3 = _ns[2] || o.zhName || "";
			var _n4 = _ns[3] || o.enName || "";
			var useId = o.useId || false;
			var _callback = o.confirm || function(){};
			
			var t = (new Date()).getTime();
			_h.append('<input type="text" name="' + _n1 + '" id="' + _n1
					+ t + '" readonly="readonly" style="cursor:pointer" />');
			_h.append('<input type="hidden" id="' + _n2 + t + '" name="' + _n2 + '" />');
			_h.append('<input type="hidden" id="' + _n3 + t + '" name="' + _n3 + '" />');
			_h.append('<input type="hidden" id="' + _n4 + t + '" name="' + _n4 + '" />');
			
			$(_obj).append(_h.toString());
			
			$('#' + _n1 + t).dictree({
				url: baseURL + "/dic/tree", // 树形字典请求地址
				param: {typeCode: o.data}, // 请求参数
				useId: useId,
				pathName: _n1 + t,
				idName: _n2 + t,
				zhName: _n3 + t,
				enName: _n4 + t,
				onlyLeafSelect: o.onlyLeafSelect || false,
				editable: o.editable || false,
				confirm: o.confirm
			});
		}
		// 附件类型多级数据字典
		function getAttachTree() {
			var _n1 = _ns[0] || o.pathName || "";
			var _n2 = _ns[1] || o.idName || "";
			var _n3 = _ns[2] || o.zhName || "";
			var _n4 = _ns[3] || o.enName || "";
			//多级数据字典当前值
			var vl = _vs[0] || "";
			var code = o.typeCode||"";
			var _callback = o.confirm || function(){};
			
			var t = (new Date()).getTime();
			_h.append('<input type="text" name="' + _n1 + '" id="' + _n1
					+ t + '" value="" data-options="required:true" class="ny_searchm2 easyui-validatebox" style="cursor:pointer" />');
			_h.append('<input type="hidden" id="' + _n2 + t + '" name="' + _n2 + '" />');
			_h.append('<input type="hidden" id="' + _n3 + t + '" name="' + _n3 + '" />');
			_h.append('<input type="hidden" id="' + _n4 + t + '" name="' + _n4 + '" />');
			
			$(_obj).append(_h.toString());
			//根据attachTypeId值，请求多级数据字典url，得到对应name等值
			$.ajax({
				url :  baseURL + "/dic/dicTreeItem",
				data: {typeCode: code,itemCode:vl},
				dateType:'json',
				success: function(data){
					if(vl==data.code){
						$('#' + _n1 + t).val(data.localeName);
						$('#' + _n2 + t).val(data.code);
						$('#' + _n3 + t).val(data.nameZh);
						$('#' + _n4 + t).val(data.nameEn);
					}
				}
			});
			
			//点击多级数据字典input事件,请求根据+businessCode+业务code过滤后的多级数据字典值
			$('#' + _n1 + t).dictree({
				url: baseURL + "/dic/treeAttach", // 树形字典请求地址
				param: {typeCode: o.typeCode,businessCode:o.businessCode==null?null:o.businessCode}, // 请求参数
				pathName: _n1 + t,
				idName: _n2 + t,
				zhName: _n3 + t,
				enName: _n4 + t,
				onlyLeafSelect: o.onlyLeafSelect || false,
				editable: o.editable || false,
				confirm: o.confirm
			});
		}
		
		// 树形数据字典
		function genDictree() {
			var _n1 = _ns[0] || o.pathName || "";
			var _n2 = _ns[1] || o.codeName || "";
			var _n3 = _ns[2] || o.zhName || "";
			var _n4 = _ns[3] || o.enName || "";
			var _callback = o.confirm || function(){};
			
			var t = (new Date()).getTime();
			_h.append('<input type="text" name="' + _n1 + '" id="' + _n1
					+ t + '" readonly="readonly" style="cursor:pointer" />');
			_h.append('<input type="hidden" id="' + _n2 + t + '" name="' + _n2 + '" />');
			_h.append('<input type="hidden" id="' + _n3 + t + '" name="' + _n3 + '" />');
			_h.append('<input type="hidden" id="' + _n4 + t + '" name="' + _n4 + '" />');
			
			$(_obj).append(_h.toString());
			
			$('#' + _n1 + t).dictree({
				url: baseURL + "/dic/tree", // 树形字典请求地址
				param: {typeCode: o.data}, // 请求参数
				pathName: _n1 + t,
				idName: _n2 + t,
				zhName: _n3 + t,
				enName: _n4 + t,
				onlyLeafSelect: o.onlyLeafSelect || false,
				editable: o.editable || false,
				confirm: o.confirm,
				checkbox:o.multi
			});
		}
		// 会计科目树形数据字典
		function genAcctree() {
			var _n1 = _ns[0] || o.pathName || "";
			var _n2 = _ns[1] || o.codeName || "";
			var _n3 = _ns[2] || o.zhName || "";
			var _n4 = _ns[3] || o.enName || "";
			var _n5 = _ns[8] || o.businessCode || "";
			var param = {year: o.year || ''};
			var _callback = o.confirm || function(){};
			
			var t = (new Date()).getTime();
			_h.append('<input type="text" name="' + _n1 + '" id="' + _n1
					+ t + '" style="cursor:pointer"/>');
			_h.append('<input type="hidden" id="' + _n2 + t + '" name="' + _n2 + '" />');
			_h.append('<input type="hidden" id="' + _n3 + t + '" name="' + _n3 + '" />');
			_h.append('<input type="hidden" id="' + _n4 + t + '" name="' + _n4 + '" />');
			
			$(_obj).append(_h.toString());
			
			$('#' + _n1 + t).acctree({
				url: baseURL + "/accitem/tree", // 树形字典请求地址
				param: param,
				pathName: _n1 + t,
				idName: _n2 + t,
				zhName: _n3 + t,
				enName: _n4 + t,
				selectPath: o.selectPath || false,
				useId:true,
				onlyLeafSelect: o.onlyLeafSelect || false,
				editable: o.editable || false,
				confirm: o.confirm
			});
		}
		//模板分类
		function genSorttree() {
			var _n1 = o.sortName || "";
			var _n2 = o.sortId || "";
			var _v1 = o.userVal || "";
			var _v2 = o.idVal || "";
			
			_h.append('<input type="text" name="' + _n1 + '" value="' + _v1 + '" readonly="readonly" style="cursor:pointer" />');
			_h.append('<input type="hidden" name="' + _n2 + '" value="' + _v2 + '"/>');
			
			$(_obj).append(_h.toString());
			
			$('input[name="' + _n1 + '"]').outree({
				url: baseURL + "/templatesort/tree",
				userName: _n1,
				idName: _n2,
                type: 1,
                leftTitle:"模板分类",//左侧弹框标题
                rightTitle:"模板名称",//右侧弹框名称
                rightTitle2:"所属分类",
				onlyLeafSelect: o.onlyLeafSelect || false,
				editable: o.editable || false,
				confirm: o.confirm
			});
		}
		function genDatepicker(){
			var _n1 = _ns[0] || "datetime";
			var _v1 = _vs[0] || "";
			var _w = o.width || 176;
			var t = (new Date()).getTime();
			_h.append('<input type="text" id="' + _n1 + t + '" name="' + _n1 + '" value="' + _v1 + '"');
			var callback = '{onpicked:function(dp){if($(this).data(\'datepickerCallback\')){$(this).data(\'datepickerCallback\')(dp.cal.getNewDateStr());}}}';
			_h.append('style="width:' + _w + 'px" class="Wdate easyui-validatebox" onClick="WdatePicker(' + callback + ')"/>');
			var ele = $(_h.toString());
			if(o.confirm){
				ele.data('datepickerCallback', o.confirm);
			}
			$(_obj).append(ele);
			
		}
		// 时间
		function genDatetime() {
			var _n1 = _ns[0] || "datetime";
			var _v1 = _vs[0] || "";
			var _w = o.width || 176;
			var _o = o.options || "";
			var t = (new Date()).getTime();
			_h.append('<input type="text" id="' + _n1 + t + '" name="' + _n1 + '" value="' + _v1 + '"');
			_h.append('style="width:' + _w + 'px" class="easyui-validatebox" data-options="' + _o + '" />');
			
			$(_obj).append(_h.toString());
			o.editable = false;
			if (_t == "date") {
				o.formatter = function(date) {
					return date.toDateString();
				};
				o.onSelect = function(date) {
					if (o.confirm) o.confirm.call(this, date.toDateString());
				};
				$("#" + _n1 + t).datebox(o);
			} else {
				o.formatter = function(date) {
					return date.toTimeString();
				};
				o.onSelect = function(date) {
					if (o.confirm) o.confirm.call(this, date.toTimeString());
				};
				$("#" + _n1 + t).datetimebox(o);
			}
		}
		
		// 人员组织树
		function genUserTree() {
			
			var orgType = o.orgType || "";
			var _n1 = _ns[0] || "user";
			var _n2 = _ns[1] || "userId";
			var _v1 = _vs[0] || "";
			var _v2 = _vs[1] || "";
			var _w = o.width || 200;
			var _ht = o.height || 20;
			var _o = o.options || "";
			var genInput = o.useInput !== false;//不创建输入框
			
			var t = (new Date()).getTime();
			
			if(genInput){
				_h.append('<input type="text" id="' + _n1 + t + '" name="' + _n1 + '" value="' + _v1 + '" readonly="readonly"');
				_h.append('		style="cursor:pointer; width:' + _w + 'px; height:' + _ht + 'px" />');
				_h.append('<input type="hidden" name="' + _n2 + '" value="' + _v2 + '"  id="' + _n2 + t +'"/>');
				
				$(_obj).append(_h.toString());
			}
			var myParam;
			if(orgType!=""){
				myParam = {orgId: o.orgId || "root",type:orgType};
			}else{
				myParam = {orgId: o.orgId || "root"};
			}
			
			var options = {
				url: baseURL + "/orgUser/tree",
				param: myParam,
				userName: _n1+t,
				idName: _n2+t,
				confirm : o.confirm
			};
			if (o.single) {
				options.onlyLeafSelect = true;
			} else {
				options.checkbox = true;
				options.cascadeCheck = true;
			}
			if(genInput){
				$("#" + _n1+ t ).outree(options);
			}else{
				$(_obj).outree(options);
			}
		}
		
		function genOrgTree() {
			
			var orgType = o.orgType || "2";
			var _n1 = _ns[0] || "org";
			var _n2 = _ns[1] || "orgId";
			var _v1 = _vs[0] || "";
			var _v2 = _vs[1] || "";
			var _w = o.width || 200;
			var _ht = o.height || 20;
			var _o = o.options || "";
			var genInput = o.useInput !== false;//不创建输入框
			
			var t = (new Date()).getTime();
			
			if(genInput){
				_h.append('<input type="text" id="' + _n1 + t + '" name="' + _n1 + '" value="' + _v1 + '" readonly="readonly"');
				_h.append('		style="cursor:pointer; width:' + _w + 'px; height:' + _ht + 'px" />');
				_h.append('<input type="hidden" name="' + _n2 + '" value="' + _v2 + '"  id="' + _n2 + t +'"/>');
				
				$(_obj).append(_h.toString());
			}
			
			var options = {
				url: baseURL + "/orgUser/tree",
				param : {type : orgType},
				userName: _n1+t,
				idName: _n2+t,
				confirm : o.confirm
			};
			if (o.single) {
				options.onlyLeafSelect = true;
			} else {
				options.checkbox = true;
				options.cascadeCheck = true;
			}
			if(o.canSelectRoot){
				options.canSelectRoot = o.canSelectRoot;
			}
			if(genInput){
				$("#" + _n1+ t ).outree(options);
			}else{
				$(_obj).outree(options);
			}
		}
	},
	
	/**
	 * 生成单点登录iframe
	 * src 框架地址
	 * ssoCallback 父页面回调方法
	 */
	genSsoIframe : function(src, ssoCallback) {
		$('body').append($('<iframe />').attr({  
            style: "display:none;width:0;height:0",
            id: "ssoLoginFrame",
            name: "ssoLoginFrame",
            src: src
        }));
		$("#ssoLoginFrame").get(0).onload = function(){
			// 父页面回调
			ssoCallback.call(window.parent);
			// 删除iframe
			setTimeout(function(){
				delIframe("#ssoLoginFrame");
			}, 500);
		};
		
		function delIframe (iframe) {
			if ($(iframe)) {
				$(iframe).remove();
			}
		}
	},

    mask:function(options){
        
        var default_setting = {
            selector: "body",
            tip: "正在处理,请稍候..."
        };
       var opts = $.extend({}, default_setting, options);
       $("<div class=\"datagrid-mask\"></div>").css({display:"block",width:"100%",height:$(window).height()}).appendTo(opts.selector); 
       $("<div class=\"datagrid-mask-msg\"></div>").html(opts.tip).appendTo(opts.selector).css({display:"block",left:($(document.body).outerWidth(true) - 190) / 2,top:($(window).height() - 45) / 2}); 
    },
     
    unmask:function(){
      $(".datagrid-mask").remove();
      $(".datagrid-mask-msg").remove();
    }	

};

/**
 * 表格操作
 */
var table = {
	/**
	 * 添加行
	 * opt = {
	 * 		button : "#addBtn",	// 添加按钮，绑定点击事件
	 * 		table : "#table",	// 表格对象
	 * 		callback : funciton(){}
	 * }
	 */
	addRow : function(opt) {
		var _b = opt.button;
		var _o = opt.table;
		var _fn = opt.callback || function(){};
		if ($(_o).length > 0) {
			if ($(_b).length > 0) {
				$(_b).bind("click", function(){
					add(opt);
					_fn.call(this);
				});
			} else {
				add(opt);
				_fn.call(this);
			}
		}
		
		function add(opt) {
			// 复制最后一行
			var $nr = $(_o).find("tr:last").clone();
			// 将复制的新行的内容清空
			$nr.find("td").each(function(i){
				if ($(this).children().is("input")) {
					$(this).find("input").each(function(){
						// 清空输入框的值
						if ($(this).not("input[type='radio']")) {
							$(this).val("");
						}
						// 选择框默认不选中
						if ($(this).is("input[type='checkbox']")) {
							$(this).removeAttr("checked");
						}
					});
				} else if (!($(this).children().is("select"))) {
					if(!($(this).children().children().is("select"))){
						
						// 清空文本内容
						$(this).text("");
					}
				}
			});
			$(_o).append($nr);
		}
	},
	
	/**
	 * 删除行
	 * opt = {
	 * 		button : "#delBtn",	// 添加按钮，绑定点击事件
	 * 		table : "#table",	// 表格对象
	 * 		batch : true,		// 是否批量删除
	 * 		order : false,		// 是否有序号
	 * 		callback : function(){}
	 * }
	 */
	delRow : function(opt) {
		var _b = opt.button;
		var _o = opt.table;
		var _fn = opt.callback || function(){};
		if ($(_b).length > 0 && $(_o).length > 0) {
			$(_b).bind("click", function(){
				_fn.call(this);
				del(opt, this);
			});
		}
		
		function del(opt, btn) {
			var _batch = opt.batch == undefined ? true : opt.batch; // 默认为批量删除
			var _order = opt.order || false; // 默认无序号
			
			if (_batch) {
				// 删除选中行
				$(_o).find("tr td:first-child input:checked").each(function(){
					var $row = $(this).parent().parent();
					if ($(_o).find("tr").length > 1) {
						$row.remove();
					} else {
						$row.find("td").each(function(i){
							if ($(this).children().is("input")) {
								$(this).find("input").each(function(){
									// 清空输入框的值
									if ($(this).not("input[type='radio']")) {
										$(this).val("");
									}
									// 选择框默认不选中
									if ($(this).is("input[type='checkbox']")) {
										$(this).removeAttr("checked");
									}
								});
							} else if (!($(this).children().is("select"))) {
								if(!($(this).children().children().is("select"))){
									
									// 清空文本内容
									$(this).text("");
								}
							}
						});
					}
				});
			} else {
				// 删除当前按钮所在行
				$(btn).parent().parent().remove();
			}
			
			// 删除行后重新排序
			if (_order) {
				$(_o).find("tr:gt(0) td:first-child").each(function(i){
					$(this).text(i + 1);
				});
			}
			
		}
	}
};

/**
 * 跨应用数据请求
 */
function ajaxpagerSort(form, sort, order){
	$(form).find(':input[name=orderByField]').val(sort);
	$(form).find(':input[name=orderType]').val(order);
	$(form).submit();
}

//激活遮罩层，此遮罩用于遮挡active控件
function activeloadMask(t){
	if(document.getElementById("SF")){
		if($("#fade").length==0){
			$(document.body).append("<iframe id='fade' class='black_overlay'></iframe>");
		}
		$("#fade").height($(document).height());
		$("#fade").show();
		if(t){
			if(!$("#fade").data('source')){
				$("#fade").data('source', t);
			}
		}
	}
}

//关闭遮罩层，此遮罩用于遮挡active控件
function destroyloadMask(t){
	if($("#fade").length>0){
		if($("#fade").data('source')){//对话框的来源
			if($("#fade").data('source') == t){//如果设置了对话框的来源，则关闭对话框必须是同一个来源，用于对话框上又打开对话框，关闭时的情况
				$("#fade").height(0);
				$("#fade").hide();
				$("#fade").removeData('source');
			}
		}else{
			$("#fade").height(0);
			$("#fade").hide();
		}
	}
}
//从表单保存的ajax响应中获取跳转到编辑页面所需要的参数，不包含表单实体id，例如
//window.location.href = '${base}/xxx/edit?id=' + json.data.id + getFormURL(json);
function getFormURL(json){
	return '&route=' + json.route + '&actors=' + json.actors + '&comment=' + json.comment;
}

//安徽-项目关联合作暂估数据接口
//param espIds:项目ID,由逗号分隔;estimateType:暂估类型
function getproCEList(param,callback){
	if(param==null)
		return;
		
	$.ajax({
        type : "post",
        url : baseURL + "/comEstimate/getproCEList",
        async : false,
        data : param,
        //dataType : "json",
        success : function(data) {
        	
        	if(data.ceProjects!=null){        		
        		if (callback) callback.call(this, data.ceProjects);      		
        	}
        }
    });
}
/**
 * 是否是流程的最后一步，并且产生凭证是Y
 * @param obj  是否凭证 的元素
 * @returns {Boolean}
 */
function isLastFlowAndPzIsY(obj){
	var _isPz ="#isPz"; // 如果没有，则选默认 TODO
	if (typeof(obj) != "undefined") { 
		_isPz=obj;
	}  	
	var value = false;
	var route = $("#workflowDiv").find('input[type=radio]:checked');
	if (route.size() == 1) {
		var transition = route.val();
		var state = $.parseJSON(transition).state;
		if (state==99) {			// 流程结束前一个步骤
			var ispz= $.trim($(_isPz).val()); //是否产生凭证 
	 		if('Y'==ispz|| '1'==ispz){value = true;}// 如果是Y则判断不为空
		}
	}
	return value;
}
/**
 * 校验不能为空
 * @param paramObj
 */
function validateAccountingNullValue(paramObj){
	if(paramObj.length>0){
		for(var i =0; i<paramObj.length; i++){
			var _s=paramObj[i]["summary"];
			var _k=paramObj[i]["subj"];
			var _c=paramObj[i]["cost"];
			var _h=paramObj[i]["money"];
			// TODO 校验是否存在，再做校验
			$(_s).readonly({enable:false}).validatebox({required:true,missingMessage:'凭证摘要不能为空'});
			$(_k).readonly({enable:false}).validatebox({required:true,missingMessage:'往来科目不能为空'});
			$(_c).readonly({enable:false}).validatebox({required:true,missingMessage:'费用类型不能为空'});
			$(_h).readonly({enable:false}).validatebox({required:true,missingMessage:'核准报账金额不能为空'});
		}
	}
}
